package org.fjsei.yewu.job.listener;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.quartz.TriggerListener;

import java.time.LocalTime;

@Slf4j
public class BusinessHoursTriggerListener implements TriggerListener {

    @Override
    public String getName() {
        return "BusinessHoursTriggerListener";
    }

    @Override
    public void triggerFired(Trigger trigger, JobExecutionContext context) {
        log.info("Trigger {}-{} fired", trigger.getKey().getName(), trigger.getKey().getGroup());
    }

    @Override
    public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) {
        LocalTime now = LocalTime.now();
        // Veto if current time is outside business hours (9 AM - 5 PM)
        /*if (now.isBefore(LocalTime.of(9, 0)) || now.isAfter(LocalTime.of(17, 0))) {
            log.info("Job execution vetoed due to non-business hours: Job {}-{}", trigger.getJobKey().getName(), trigger.getJobKey().getGroup());
            return true; // Prevent the job from running
        }*/

        if (now.isAfter(LocalTime.of(23, 0))) {
            log.info("全局拦截的vetoed 时间不对的，被拦截的job算完成: Job {}-{}", trigger.getJobKey().getName(), trigger.getJobKey().getGroup());
            return true; // Prevent the job from running
        }
        return false; // Allow the job to proceed
    }

    @Override
    public void triggerMisfired(Trigger trigger) {
        log.info("Trigger Misfired. Trigger{}-{}", trigger.getKey().getName(), trigger.getKey().getGroup());
        // Handle misfires
    }

    @Override
    public void triggerComplete(Trigger trigger, JobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode) {
        // Called when the trigger finishes execution
        log.info("Trigger complete. Trigger {}-{}", trigger.getKey().getName(), trigger.getKey().getGroup());
    }
}
